﻿using System;
using System.IO;

namespace Server
{
  class TFileProcessor : TRequestProcessor
  {
    private void Output(string FileName)
    {
      FileStream stream = new FileStream(FileName, FileMode.Open, FileAccess.Read);
      byte[] buffer = new byte[stream.Length];
      stream.Read(buffer, 0, (int)stream.Length);

      base.Output(buffer);
    }

    private void BuildIndex()
    {
      // TODO: build index dynamically in debug mode

      Output("Pages\\index.html");
    }

    protected override void ProcessRequest(object Param)
    {
      string LocalPath = Request.Url.LocalPath
        .Replace(".", "")
        .Replace("/", "")
        .Replace("\\", "")
        .ToUpper();

      if (LocalPath == "")
      {
        BuildIndex();
      }
      else if (LocalPath.StartsWith("/forms".ToUpper()))
      {
        // TODO: add config file to avoid hardcode

        string FormName = @"..\..\..\Forms\Generated\" + LocalPath.Replace(@"/forms/".ToUpper(), "");
        if (!File.Exists(FormName))
          Output(@"Pages\\NotFound.html");
        else
          Output(FormName);
      }
      else
      {
        Response.OutputStream.Close();
      }
    }
  }
}
